package ldh.im.util;

import io.netty.buffer.ByteBuf;

import java.nio.charset.Charset;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class ByteBufHelp {

    public static final int AUTH_LENGTH = 4;

    public static int writeString(ByteBuf byteBuf, String str, Charset charset) {
        if (str == null) {
            byteBuf.writeInt(0);
            return 4;
        }
        byte[] bytes = str.getBytes(charset);
        byteBuf.writeInt(bytes.length);
        if (bytes.length > 0) {
            byteBuf.writeBytes(bytes);
        }
        return 4 + bytes.length;
    }

    public static String readString(ByteBuf byteBuf, Charset charset) {
        int length = byteBuf.readInt();
        return readString(byteBuf, length, charset);
    }

    public static String readString(ByteBuf byteBuf, int length, Charset charset) {
        if (length > 0) {
            byte[] bytes = new byte[length];
            byteBuf.readBytes(bytes);
            return new String(bytes, charset);
        }
        return null;
    }

    public static char[] readChars(ByteBuf byteBuf) {
        int length = byteBuf.readInt();
        char[] data = new char[length];
        for(int i=0; i<length; i++) {
            data[i] = byteBuf.readChar();
        }
        return data;
    }

    public static byte[] getHeadBytes(ByteBuf byteBuf) {
        int length = AUTH_LENGTH + 1;
        if (byteBuf.readableBytes() < length) throw new RuntimeException("头部信息不正确");
        byte[] data = new byte[AUTH_LENGTH];
        for(int i=1; i<length; i++) {
            data[i-1] = byteBuf.getByte(i);
        }
        return data;
    }

    public static void writeChars(ByteBuf byteBuf, char[] chars) {
        byteBuf.writeInt(chars.length);
        for(int i=0; i<chars.length; i++) {
            byteBuf.writeChar(chars[i]);
        }
    }

    public static LocalDateTime readDateTime(ByteBuf byteBuf) {
        long time = byteBuf.readLong();
        LocalDateTime longToLocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        return longToLocalDateTime;
    }

    public static void readDateTime(ByteBuf byteBuf, LocalDateTime localDateTime) {
        Instant localDateTimeToInstant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        Date date = Date.from(localDateTimeToInstant);
        long time = date.getTime();
        byteBuf.writeLong(time);
    }

    public static int getLength(ByteBuf byteBuf) {
       return byteBuf.getInt(1 + AUTH_LENGTH);
    }

}
